<template>
  <div class="aa">
    <el-row>
      <el-col :span="2">
        <el-autocomplete
            v-model="createUser"
            :fetch-suggestions="querySearch"
            placeholder="输入创建人姓名搜索"
            size="small"
            @select="handleSelect"
            @change="getTable"
        >
          <template v-slot="{ item }">
            <div class="name">{{ item.createUser }}</div>
          </template>
        </el-autocomplete>
      </el-col>

      <el-col :span="3">
        <el-date-picker
            v-model="createTime"
            size="small"
            value-format="YYYY-MM-DD"
            @change="pick($event)"
            type="date"
            placeholder="选择日期">
        </el-date-picker>
      </el-col>

      <el-col :span="2">
        <el-button size="medium" @click="showForm('form')">录入数据</el-button>
      </el-col>
      <el-col :span="24">
        <el-table
            :data="tableData.slice((currentPage-1)*pageSize,currentPage*pageSize)"
            border
            stripe
            style="width: 100%"
            show-summary
            :summary-method="getSummaries"
            :default-sort = "{prop: 'date', order: 'descending'}"
        >
          <el-table-column
              prop="id"
              label="编号"
              width="190"
          >
          </el-table-column>
          <el-table-column
              prop="eventCreateTime"
              label="事件处发时间"
              width="140"
              sortable>
          </el-table-column>
          <el-table-column
              prop="eventContent"
              width="100"
              label="事件内容">
          </el-table-column>

          <el-table-column
              prop="advanceAmount"
              width="120"
              label="预支付金额(元)">
          </el-table-column>

          <el-table-column
              prop="cashAmount"
              width="120"
              label="现支付金额(元)">
          </el-table-column>


          <el-table-column
              prop="isFlag"
              width="150"
              :formatter="formatFlag"
              label="是否超出预支付金额">
          </el-table-column>

          <el-table-column
              prop="remark"
              width="290"
              label="详细备注">
          </el-table-column>

          <el-table-column
              prop="remedialPlan"
              width="290"
              label="超出预支付金额补救方案">
          </el-table-column>


          <el-table-column
              prop="createUser"
              width="100"
              label="事件创建人">
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button
                  size="mini"
                  @click="handleEdit(scope.$index,scope.row)">编辑</el-button>
              <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)">删除</el-button>

              <!--              <el-button-->
              <!--                  size="mini"-->
              <!--                  type="info"-->
              <!--                  @click="initData(scope.$index, scope.row)">数据初始化</el-button>-->
            </template>
          </el-table-column>

        </el-table>

        <el-pagination
            background
            layout="prev, pager, next"
            :total="tableData.length"
            @current-change="currentChange"
            @size-change="sizeChange"
            page-size="15"
        >
        </el-pagination>

      </el-col>
    </el-row>
    <el-dialog title="编辑账本信息" v-model="dialogFormVisible"  destroy-on-close >
      <el-form :model="form" :rules="valid" ref="form">
        <el-form-item label="账本写入人主键" :label-width="20" v-show="false">
          <el-input v-model="form.id" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="默认标识" :label-width="20" v-show="false">
          <el-input v-model="form.deleteFlag" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="账本写入人" :label-width="20" prop="createUser">
          <el-input v-model="form.createUser" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="账本写入日期"  prop="eventCreateTime">
          <el-date-picker type="date" placeholder="选择日期" v-model="form.eventCreateTime" style="width: 100%;"  value-format="YYYY-MM-DD"></el-date-picker>
        </el-form-item>
        <el-form-item label="事件内容" :label-width="20" prop="eventContent">
          <el-input v-model="form.eventContent" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="预支付金额" :label-width="20" prop="advanceAmount">
          <el-input v-model="form.advanceAmount" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="现支付金额" :label-width="20" prop="cashAmount">
          <el-input v-model="form.cashAmount" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="是否超出预支付金额" prop="isFlag">
          <el-radio-group v-model="form.isFlag" >
            <el-radio label="1">是</el-radio>
            <el-radio label="2">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="详细说明" :label-width="20" >
          <el-input v-model="form.remark" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="超出预支付金额的补救描述" :label-width="20" >
          <el-input v-model="form.remedialPlan" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('form')">提交</el-button>
          <el-button @click="resetForm('form')">重置</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>
  </div>

</template>

<script>
import axios from 'axios'
import {ElMessage} from 'element-plus'
export default {
  name: "userTable",
  props:{

  },

  created() {
    // 加载远程搜索框里的数据
    axios.get("http://cong.shart.work/api/users",{
      params:{}
    }).then((response)=> {
      this.restaurants=response.data;
    }).catch((res)=> {
      console.log(res)
    })

    // 给表格填充数据
    let tableList=JSON.parse( localStorage.getItem("table"));
    if(tableList) {
      this.tableData= tableList
    }else{
      // 分页
      axios.get("http://cong.shart.work/api/page",{
        params:{}
      }).then((response)=> {
        this.tableData=response.data;
        console.log(this.tableData)
      }).catch((res)=> {
        console.log(res)
      })
    }


  },
  methods:{
    /**********************************************************编辑*******************************************************/
    handleEdit(index, row) {
      console.log(index,row)
      this.dialogFormVisible=true;
      // 赋值写入
      this.form.createUser= row.createUser;
      this.form.eventContent=row.eventContent;
      this.form.eventCreateTime=row.eventCreateTime;
      this.form.advanceAmount=row.advanceAmount;
      this.form.cashAmount=row.cashAmount;
      this.form.isFlag=row.isFlag;
      this.form.remark=row.remark;
      this.form.remedialPlan=row.remedialPlan;
      this.form.id=row.id;
    },
    handleDelete(index, row) {
      console.log(index, row);
      this.tableData.splice(index,1);
      localStorage.setItem("table",JSON.stringify(this.tableData))
    },
    initData(index, row){
      let tableList=JSON.parse( localStorage.getItem("table"));
      if(!tableList) {
        ElMessage.error("本来就是原始数据,你点你爷!!!")
        setTimeout(() =>{
          ElMessage.error("大傻逼")
        },1000);
      }
      localStorage.removeItem("table");
      console.log(index, row);
      axios.get("http://192.168.50.58:8080/api/attenceConfirm/getEmp",{
        params:{}
      }).then((response)=> {
        this.tableData=response.data.data;
      }).catch((res)=> {
        console.log(res)
      })

    },
    /**********************************************************分页，当前页页码重新计算*******************************************************/
    currentChange:function (current){
      this.currentPage= current;
    },
    sizeChange:function (pageSize){
      this.pageSize=pageSize
    },
    /**********************************************************远程检索处罚*******************************************************/
    querySearch(queryString, cb) {
      if (this.createUser=='' || this.createUser==null)
        this.getTable();
      var restaurants = this.restaurants;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      cb(results);
    },
    createFilter(queryString) {
      return (state) => {
        console.log(state.value)
        return  (state.createUser.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      };
    },
    /**********************************************************远程检索函数*******************************************************/
    handleSelect(item){
      axios.get("http://cong.shart.work/api/page",{
        params:{"createUser":item.createUser}
      }).then((response)=> {
        this.tableData=response.data;
      }).catch((res)=> {
        console.log(res)
      })
    },
    /**********************************************************日期搜索*******************************************************/
    pick(event){
      // 分页
      axios.get("http://cong.shart.work/api/page",{
        params:{"createTime":event}
      }).then((response)=> {
        this.tableData=response.data;
        console.log(this.tableData)
      }).catch((res)=> {
        console.log(res)
      })
    },
    /**********************************************************初始化*******************************************************/
    getTable(){
      // 分页
      axios.get("http://cong.shart.work/api/page",{
        params:{}
      }).then((response)=> {
        this.tableData=response.data;
        console.log(this.tableData)
      }).catch((res)=> {
        console.log(res)
      })
      this.createTime='';
      this.createUser='';
    },
    /**********************************************************提交表单*******************************************************/
    submitForm(formName) {
      console.log(this.form)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 修改
          if (this.form.id){
            axios.post("http://cong.shart.work/api/saveAndFlush", this.form).then((response)=> {
              if(response.data==200){
                this.$message.success('修改成功!!!!');
                this.dialogFormVisible=false;
                this.$refs[formName].resetFields();
                this.getTable();
              }
            }).catch((res)=> {
              this.$message.error(res);
            })
          }else{
            this.form.deleteFlag=0;
            axios.post("http://cong.shart.work/api/saveAndFlush", this.form).then((response)=> {
              if(response.data==200){
                this.$message.success('新增成功!!!!');
                this.dialogFormVisible=false;
                this.$refs[formName].resetFields();
                this.getTable();
              }
            }).catch((res)=> {
              this.$message.error(res);
            })
          }


        } else {
          this.$message.error('校验错误,请检查输入项！！！');
          return false;
        }
      });
    },
    /**********************************************************清空表单*******************************************************/
    resetForm(formName) {
      this.form={};
      this.$refs[formName].resetFields();
    },
    /**********************************************************显示表单*******************************************************/
    showForm(formName){
      console.log(formName)
      this.form={};
      this.dialogFormVisible=true;
    },
    /**********************************************************关闭表单*******************************************************/
    closeForm(){
      this.dialogFormVisible=false;
      this.form={};
    },
    /**********************************************************合计*******************************************************/
    getSummaries(param){
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '预支出总金额/已支出金额';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          if (sums[index] == 0) {
            sums[index] = '';
            // index=5 指的是是否超出预算金额那列
          }else if(index==5){
            sums[index] = '';
          }else {
            sums[index] += ' 元';
          }


        } else {
          sums[index] = '';
        }
      });
      return sums;
    },
    formatFlag(row,column){
      console.log(111111111)
      let data = row[column.property];
      console.log(data);
      if(data=='1'){
        return "是";
      }else {
        return  "否";
      }
    },
    deicmFormat(row,column){

      let data = row[column.property];
        return  data+'元';
    },
  },
  data(){
    return {
      //表格
      tableData:[],
      //创建人检索
      createUser:'',
      // 当前页
      currentPage:1,
      // 每页多少条，用于计算页码分页等
      pageSize:15,
      // 创建人远程数据
      restaurants: [],
      state: '',
      timeout:  null,
      // 创建日期
      createTime:'',
      // 表单弹出框是否显示
      dialogFormVisible:false,
      // 表单提交的参数
      form:
          {
            "createUser":'',
            "eventCreateTime":'',
            "eventContent":'',
            'advanceAmount': 0.00,
            'cashAmount':0.00,
            'isFlag':2,
            'remark':'',
            'remedialPlan':'',
            "id":'',
            "deleteFlag":0
          },
      //校验规则
      valid: {
        createUser:[
          { required: true, message: '账本写入人不能为空', trigger: 'blur' },
          { min: 1, max: 6, message: '长度在 1 到 6 个字符', trigger: 'blur' }
        ],
        eventCreateTime:[
          { type: 'date', required: true, message: '请选择账本写入日期', trigger: 'blur' }
        ],
        eventContent:[
          { required: true, message: '事件内容不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        advanceAmount:[
          { required: true, message: '预支付金额不能为空'},
          { type: 'number', message: '预支付金额只能是数字',trigger: 'blur',transform:(value)=>{return Number(value)}}
        ],
        cashAmount:[
          { required: true, message: '现支付金额不能为空'},
          { type: 'number', message: '现支付金额只能是数字',transform:(value)=>{return Number(value)},trigger: 'blur'}
        ],
        isFlag:[
          { required: true, message: '请选择是否超出预支付金额', trigger: 'change' }
        ]
      }
    }
  }
}
</script>

<style scoped>

</style>
